package com.ziroom.zifamily.zfcensor.mq;

import com.alibaba.rocketmq.client.exception.MQBrokerException;
import com.alibaba.rocketmq.client.exception.MQClientException;
import com.alibaba.rocketmq.client.producer.DefaultMQProducer;
import com.alibaba.rocketmq.client.producer.SendResult;
import com.alibaba.rocketmq.common.message.Message;
import com.alibaba.rocketmq.remoting.exception.RemotingException;
import com.ziroom.zifamily.zeus.json.Jsonable;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;

/**
 * <p>
 * <PRE>
 * <BR>    修改记录
 * <BR>-----------------------------------------------
 * <BR>    修改日期         修改人          修改内容
 * </PRE>
 *
 * @author cuiyh9
 * @version 1.0
 * @Date Created in 2018年11月28日 17:28
 * @since 1.0
 */
@Slf4j
@Component
public class RocketProviderClient {

    private static final String CHARSET_UTF8 = "utf-8";

    public static final String TOPIC_CENSOR_FEED = "topic_censor_feed";

    @Autowired
    private DefaultMQProducer defaultMQProducer;

    /**
     * 发送消费
     * @param topic
     * @param jsonable
     */
    public void sendMsgByTopic(String topic, Jsonable jsonable) {
        sendMsgByTopic(topic, jsonable.toJsonStr());
    }

    /**
     * 发送消费
     * @param topic
     * @param text
     */
    public void sendMsgByTopic(String topic, String text) {

        try {
            Message msg = new Message(topic, text.getBytes(CHARSET_UTF8));
            SendResult sendResult = defaultMQProducer.send(msg);
            log.info("sendMsgByTopic:{},text:{}", sendResult, text);
        } catch (MQClientException e) {
            e.printStackTrace();
        } catch (RemotingException e) {
            e.printStackTrace();
        } catch (MQBrokerException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

    }
}
